package com.ruoyi.app.utils;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SendCodeUtil {

    @Value("${api.captcha.prefix.email}")
    private String Email_Prefix;

    @Value("${api.captcha.prefix.phone}")
    private String Phone_Prefix;

    @Resource
    private RedisCache redisCache;

    /**
     * 发送手机验证码
     */
    public void sendPhoneCode(Long phone) {
        // 限制发送次数
        if (redisCache.hasKey(Phone_Prefix + ":" + phone)) {
            throw new ServiceException("验证码已发送，请勿重复发送");
        }

        // 生成验证码
        String code = String.valueOf((Math.random() * 9 + 1) * 100000);

        log.info("手机号：{} 验证码：{}", phone, code);

        // 存入缓存
        redisCache.setCacheObject(Phone_Prefix + ":" + phone, code, 5, TimeUnit.MINUTES);
    }

    /**
     * 发送邮箱验证码
     */
    public void sendEmailCode(String email) {
        // 限制发送次数
        if (redisCache.hasKey(Email_Prefix + ":" + email)) {
            throw new ServiceException("验证码已发送，请勿重复发送");
        }

        // 生成验证码
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));

        log.info("邮箱：{} 验证码：{}", email, code);

        // 存入缓存
        redisCache.setCacheObject(Email_Prefix + ":" + email, code, 5, TimeUnit.MINUTES);
    }
}
